Popular Searches
Popular Course Categories
Popular Courses

Creating Dynamic Web Pages Using JSP

Creating Dynamic Web Pages Using JSP

JavaServer Pages (JSP) Development

Creating Dynamic Web Pages Using JSP

Course: Advanced Java Training

Topic: Creating Dynamic Web Pages Using JavaServer Pages (JSP)

Course Link: Advanced Java Training Course

Demo Link: Register for a Free Course Demo

Website: JustAcademy


1. Introduction to Dynamic Web Pages Using JSP

JavaServer Pages (JSP), now commonly referred to as Jakarta Server Pages in modern Jakarta EE environments, is a server-side technology used to create dynamic web pages using HTML, Java-based application components, Expression Language (EL), and tag libraries. JSP makes it possible to display information that changes according to user input, database records, login status, session data, and application logic.

Unlike a static HTML page, which generally displays the same predefined content to every visitor, a dynamic JSP page can generate different responses for different users or requests. For example, an e-commerce application can display a user's name, shopping cart, product list, order history, and personalized recommendations.

JSP pages are processed by a JSP container, which translates JSP content into servlet code and compiles it when necessary. The resulting servlet executes on the server and generates a response, commonly HTML, that is sent to the browser.

Examples of Dynamic Web Pages

  • A login page that displays a personalized welcome message.
  • An employee dashboard that displays employee information from a database.
  • An online shopping page that displays products and prices.
  • A registration page that displays validation messages.
  • A student portal that displays marks, attendance, and course details.
  • A booking application that displays reservation information.

2. Learning Objectives

After completing this topic, learners should be able to:

  • Understand JSP and its role in Java web applications.
  • Explain the difference between static and dynamic web pages.
  • Understand how JSP works with servlets and web servers.
  • Create JSP pages using HTML and JSP syntax.
  • Use JSP directives, Expression Language, and standard actions.
  • Retrieve request parameters and display dynamic content.
  • Use JavaBeans and request, session, and application scopes.
  • Display collections and conditional content using JSTL.
  • Build a small dynamic web application.
  • Apply security and maintainability best practices.

3. What Is JSP?

JSP is a server-side view technology that enables developers to build web pages using template content and dynamic expressions. It is built on the servlet model, so a JSP page is ultimately handled by a servlet container.

Key Characteristics

  • Server-side processing: JSP logic and expressions are evaluated on the server.
  • HTML integration: HTML can be combined with dynamic values.
  • Servlet integration: JSP works with servlets to process requests and generate responses.
  • Expression Language: EL provides convenient access to request data and JavaBean properties.
  • Tag libraries: JSTL and custom tags help reduce Java code embedded in pages.
  • Reusable components: Shared page fragments can be included in multiple JSP pages.
  • Container-managed lifecycle: The JSP container manages translation, compilation, initialization, and execution.

4. Static Web Pages vs. Dynamic Web Pages

Feature Static Web Page Dynamic Web Page Using JSP
Content Usually predefined Can change based on data and requests
Processing Usually served directly as a file Processed by the server-side application
User input Does not automatically process input Can display results based on submitted input
Database integration Not built into the page itself Can display data supplied by Java application components
Personalization Limited without additional technology Can display user-specific content
Examples Static information page Dashboard, product catalog, profile page

5. How JSP Creates Dynamic Web Pages

When a browser requests a JSP page, the web server and JSP container process the request. The container translates the JSP into a servlet implementation and compiles it if needed. The servlet then executes, creates the response, and sends it to the browser.

Request Processing Flow

  1. The user enters a JSP URL or clicks a link.
  2. The browser sends an HTTP request to the web server.
  3. The servlet container identifies the requested JSP page.
  4. If required, the JSP container translates the JSP into servlet source code and compiles it.
  5. The generated servlet processes the request.
  6. Dynamic values are evaluated and combined with the page's template content.
  7. The server sends the generated response to the browser.
  8. The browser renders the received HTML.

Important: The browser normally receives the generated response, not the original JSP source code. JSP processing takes place on the server.

6. Setting Up a JSP Development Environment

To develop and run JSP pages, prepare the following tools:

  • Java Development Kit (JDK): Provides the Java compiler and runtime.
  • IDE: Eclipse IDE for Enterprise Java and Web Developers, IntelliJ IDEA, or another compatible editor.
  • Servlet container: Apache Tomcat or another JSP-compatible container.
  • Web browser: Used to access and test the application.
  • Build tool: Maven or Gradle can manage project dependencies and packaging.

Compatibility Consideration

Choose the JSP and servlet API versions that match your server. Older Java EE projects commonly use packages beginning with javax.servlet, while modern Jakarta EE projects use packages beginning with jakarta.servlet. These APIs are not interchangeable without the appropriate migration and compatible server version.

Typical Maven Web Application Structure

my-jsp-application/
├── pom.xml
└── src/
    └── main/
        ├── java/
        │   └── com/example/web/
        │       └── GreetingServlet.java
        └── webapp/
            ├── index.jsp
            └── WEB-INF/
                └── web.xml

The exact folder structure may vary according to the IDE and build configuration. A deployment descriptor is optional in many annotation-based applications.

7. Creating Your First Dynamic JSP Page

Create a file named index.jsp inside the web application's web root. The following example uses a JSP Expression Language expression to display the current server-side date and time through a request attribute. A servlet or controller should set this attribute before forwarding to the page; the example below first demonstrates a simple EL expression using a predefined request attribute.

Example 1: Displaying a Dynamic Value

<%@ page contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Dynamic JSP Page</title>
</head>
<body>
    <h1>Welcome to JSP</h1>
    <p>Message: ${requestScope.message}</p>
</body>
</html>

For the expression to display a message, the application must place a value under the request attribute name message before forwarding to this JSP. If the attribute has not been set, the expression may render as an empty value.

Example 2: Supplying the Dynamic Value with a Servlet

package com.example.web;

import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@WebServlet("/welcome")
public class GreetingServlet extends HttpServlet {
    @Override
    protected void doGet(
            HttpServletRequest request,
            HttpServletResponse response)
            throws ServletException, IOException {

        request.setAttribute(
            "message",
            "Your JSP page is displaying dynamic content."
        );

        request.getRequestDispatcher("/index.jsp")
               .forward(request, response);
    }
}

In this example, the servlet sets the message request attribute and forwards the same request to the JSP page. The JSP reads the value using ${requestScope.message}. Because the servlet uses the jakarta.servlet namespace, the project must use a compatible Jakarta-based servlet container.

8. JSP Directives

JSP directives provide information to the container during page translation and compilation. They help configure page behavior and identify resources used by the page.

8.1 Page Directive

The page directive specifies page-level settings, such as the content type, character encoding, imported classes, and error page configuration.

<%@ page contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"
    import="java.time.LocalDate" %>

<p>JSP page configuration example.</p>

8.2 Include Directive

The include directive includes the contents of another file during JSP translation. It is useful for shared page fragments such as headers and navigation menus.

<%@ include file="header.jsp" %>
<main>
    <h2>Dashboard</h2>
    <p>Main page content goes here.</p>
</main>
<%@ include file="footer.jsp" %>

8.3 Taglib Directive

The taglib directive makes a tag library available to a JSP page. For example, a JSTL core library can be declared using the URI and dependency configuration appropriate to the project's JSTL version.

<%@ taglib prefix="c"
    uri="jakarta.tags.core" %>

For older JSTL versions, the library URI may be different. Always use the URI documented for the JSTL implementation installed in your project.

9. JSP Scripting Elements

JSP supports scripting elements that embed Java code into a page. They are part of the JSP language, but modern applications should generally prefer Expression Language, JSTL, and controller classes over scriptlets.

Element Syntax Purpose
Declaration <%! ... %> Declares fields or methods in the generated servlet class.
Scriptlet <% ... %> Embeds Java statements in JSP processing.
Expression <%= ... %> Evaluates a Java expression and writes its value to the response.

Example: JSP Expression (Legacy Syntax)

<%
    String courseName = "Advanced Java";
%>
<p>Course: <%= courseName %></p>

This example demonstrates JSP syntax, but it should not be treated as the preferred design for production applications. Keeping business logic in Java classes and using EL to render prepared values makes pages easier to test and maintain.

10. Using Expression Language (EL)

Expression Language makes it easier to access data exposed to a JSP page without writing Java scriptlets. Immediate EL expressions use the ${...} syntax.

Common EL Examples

<p>User: ${requestScope.userName}</p>
<p>Course: ${requestScope.courseName}</p>
<p>Search term: ${param.keyword}</p>
<p>Session user: ${sessionScope.loggedInUser}</p>

These expressions read request attributes, request parameters, and session attributes. The application must supply the corresponding values where applicable.

Common EL Implicit Objects

Object Purpose Example
param Accesses a single request parameter ${param.keyword}
paramValues Accesses multiple values for a parameter ${paramValues.category[0]}
requestScope Accesses request attributes ${requestScope.message}
sessionScope Accesses session attributes ${sessionScope.user}
applicationScope Accesses application-wide attributes ${applicationScope.siteName}
header Accesses HTTP request headers ${header["User-Agent"]}

11. Creating a Dynamic Page Using Request Parameters

Request parameters allow a JSP-based application to respond to values submitted through a URL or HTML form. For maintainability, a servlet should normally validate input and prepare the data before forwarding to the JSP.

HTML Form

<form action="greet" method="get">
    <label for="name">Enter your name:</label>
    <input type="text" id="name" name="name" required>
    <button type="submit">Submit</button>
</form>

Servlet Controller

package com.example.web;

import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@WebServlet("/greet")
public class GreetServlet extends HttpServlet {
    @Override
    protected void doGet(
            HttpServletRequest request,
            HttpServletResponse response)
            throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");

        String name = request.getParameter("name");

        if (name == null || name.isBlank()) {
            name = "Guest";
        }

        request.setAttribute("displayName", name);
        request.getRequestDispatcher("/greeting.jsp")
               .forward(request, response);
    }
}

JSP View

<%@ page contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Greeting</title>
</head>
<body>
    <h1>Welcome, ${requestScope.displayName}!</h1>
</body>
</html>

Security note: User-provided input must be validated and safely encoded before being inserted into HTML. EL output is not automatically safe in every HTML context. For production applications, use context-appropriate output encoding or a trusted escaping tag/library, such as a correctly configured JSTL output tag.

12. Displaying Conditional and Repeated Content with JSTL

The Jakarta Standard Tag Library (JSTL) provides tags for common presentation tasks such as conditions and iteration. It helps keep JSP views readable without embedding Java loops and conditions directly into the page.

Conditional Content

<%@ taglib prefix="c"
    uri="jakarta.tags.core" %>

<c:if test="${not empty requestScope.userName}">
    <p>Welcome, <c:out value="${requestScope.userName}"/>!</p>
</c:if>

<c:if test="${empty requestScope.userName}">
    <p>Welcome, guest!</p>
</c:if>

Repeating Through a Collection

<%@ taglib prefix="c"
    uri="jakarta.tags.core" %>

<h2>Available Courses</h2>
<ul>
    <c:forEach var="course"
        items="${requestScope.courses}">
        <li><c:out value="${course}"/></li>
    </c:forEach>
</ul>

The controller should populate the courses request attribute with a collection before forwarding to the JSP. Confirm that the JSTL dependency and tag library URI match the selected container and library versions.

13. Using JavaBeans to Separate Data from the View

A JavaBean is a Java class that commonly provides private fields and public getter and setter methods. JSP pages can access bean properties using EL when the bean is exposed in a suitable scope.

Example JavaBean

package com.example.model;

public class Course {
    private String name;
    private String level;

    public Course() {
    }

    public Course(String name, String level) {
        this.name = name;
        this.level = level;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getLevel() {
        return level;
    }

    public void setLevel(String level) {
        this.level = level;
    }
}

Accessing Bean Properties in JSP

<p>Course: ${requestScope.course.name}</p>
<p>Level: ${requestScope.course.level}</p>

Before forwarding to the JSP, a controller can create a Course object and store it as a request attribute named course. This approach separates Java data handling from HTML presentation.

14. JSP Scopes and Dynamic Data

JSP data can be stored in different scopes according to how long it should remain available and which parts of the application need access to it.

Scope Lifetime Typical Use
Page During processing of the current JSP page Temporary page-specific values
Request During a single request, including a server-side forward Form results and display data
Session Across requests associated with a user session Login state and shopping cart data
Application For the lifetime of the web application Shared configuration or application-wide values

Choose the smallest scope that satisfies the requirement. Avoid storing sensitive or user-specific information in application scope, and do not assume that request attributes automatically survive a redirect to a new request.

15. Reusing Page Components with Includes

Most web applications contain common elements such as headers, navigation bars, sidebars, and footers. JSP supports reusable fragments that reduce duplication and make page updates easier.

Translation-Time Include

<%@ include file="header.jsp" %>
<main>
    <h1>Student Dashboard</h1>
    <p>Dashboard content appears here.</p>
</main>
<%@ include file="footer.jsp" %>

Request-Time Include

<jsp:include page="/shared/navigation.jsp" />

The include directive inserts a file during JSP translation, whereas the jsp:include action includes the output of another resource during request processing. Select the approach according to whether the fragment needs request-time processing.

16. JSP with MVC Architecture

Model-View-Controller (MVC) separates an application into three responsibilities:

  • Model: Represents application data and business operations, often through Java classes and services.
  • View: Displays the prepared data. JSP commonly performs this role.
  • Controller: Receives requests, validates input, invokes services, and selects the response view. A servlet commonly performs this role.

Example MVC Request Flow

  1. The browser sends a request to a servlet controller.
  2. The controller validates parameters and invokes the required service or model.
  3. The model or service retrieves or processes application data.
  4. The controller places the required data into request attributes.
  5. The controller forwards the request to a JSP view.
  6. The JSP renders the prepared values into HTML.
  7. The server sends the HTML response to the browser.

MVC helps avoid putting database queries, authentication logic, and complex business rules directly inside JSP pages. It also makes the application easier to test and maintain.

17. Example Mini Project: Student Information Page

This mini project demonstrates how a dynamic JSP page can display information supplied by a servlet. It can be expanded to retrieve student details from a database through a service or repository class.

Step 1: Prepare the JSP View

<%@ page contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Student Information</title>
</head>
<body>
    <h1>Student Information</h1>
    <p>Name: ${requestScope.studentName}</p>
    <p>Course: ${requestScope.courseName}</p>
    <p>Status: ${requestScope.status}</p>
</body>
</html>

Step 2: Prepare the Servlet Controller

package com.example.web;

import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@WebServlet("/student")
public class StudentServlet extends HttpServlet {
    @Override
    protected void doGet(
            HttpServletRequest request,
            HttpServletResponse response)
            throws ServletException, IOException {

        request.setAttribute("studentName", "Aarav Sharma");
        request.setAttribute("courseName", "Advanced Java");
        request.setAttribute("status", "Active");

        request.getRequestDispatcher("/student.jsp")
               .forward(request, response);
    }
}

Step 3: Run the Application

  1. Create a compatible Java web project in your IDE.
  2. Place the servlet class in the correct Java package.
  3. Save the JSP file as student.jsp in the web application root.
  4. Deploy the application to a compatible servlet container.
  5. Open the application's /student URL in the browser.
  6. Verify that the JSP displays the values supplied by the servlet.

Expected result: The browser displays the student name, course name, and status using values prepared on the server.

Extension: Replace the hard-coded values with records returned by a service that reads student data from a database. Use prepared SQL statements in the data-access layer and keep database access out of the JSP.

18. Form Validation and Dynamic Feedback

Dynamic JSP pages often display success messages, validation errors, and results from submitted forms. The controller should validate user input before forwarding to the view.

  • Check required fields and acceptable input formats.
  • Validate input on the server even if browser-side validation is also used.
  • Set an error or success message as a request attribute.
  • Forward to the JSP to display the result.
  • Use safe output encoding when rendering user-supplied values.
  • Preserve valid form values only when it is appropriate and safe to do so.

Displaying a Validation Message

<%@ taglib prefix="c"
    uri="jakarta.tags.core" %>

<c:if test="${not empty requestScope.errorMessage}">
    <p role="alert">
        <c:out value="${requestScope.errorMessage}"/>
    </p>
</c:if>

<c:if test="${not empty requestScope.successMessage}">
    <p>
        <c:out value="${requestScope.successMessage}"/>
    </p>
</c:if>

For this example, ensure the correct JSTL dependency and tag library URI are configured. The controller must set the relevant request attributes before forwarding to the page.

19. JSP Security Best Practices

  • Encode output: Encode untrusted values for the context where they are displayed to help prevent cross-site scripting (XSS).
  • Validate input: Validate all values received from forms, query strings, headers, and other untrusted sources.
  • Use authentication and authorization: Protect restricted pages and actions at the server or controller level, not merely by hiding links in the JSP.
  • Use HTTPS: Protect credentials and sensitive data while in transit.
  • Protect state-changing requests: Use appropriate CSRF defenses for authenticated forms and actions.
  • Avoid exposing exceptions: Show friendly error pages while logging diagnostic details securely on the server.
  • Keep secrets out of views: Never print passwords, API keys, connection strings, or sensitive session information.
  • Use prepared statements: When database operations are required, use parameterized queries in the data-access layer.
  • Restrict direct access where appropriate: Place internal JSP views under WEB-INF when they should only be reached through a controller.
  • Use supported dependencies: Keep the servlet container, JSP implementation, and tag libraries compatible and maintained.

20. Best Practices for Maintainable JSP Pages

  • Keep JSP pages focused on presentation rather than business logic.
  • Prefer EL and JSTL over scriptlets in new or maintained JSP views.
  • Use servlets or framework controllers to handle requests.
  • Use service and repository classes for business operations and data access.
  • Reuse common page fragments instead of duplicating markup.
  • Use descriptive attribute names and consistent page structure.
  • Set the correct response content type and character encoding.
  • Use meaningful HTML semantics and accessible form labels.
  • Handle missing values and invalid states gracefully.
  • Test both successful requests and error conditions.

21. Common JSP Errors and Troubleshooting

Problem Possible Cause Recommended Solution
JSP page returns 404 Incorrect path or undeployed application Verify deployment status, context path, and file location.
EL expression displays blank Attribute not set or incorrect scope/name Check the controller and confirm the attribute name and scope.
JSP compilation error Invalid JSP syntax, incompatible library, or missing dependency Review server logs and verify syntax and versions.
JSTL tag is not recognized Incorrect taglib URI or missing JSTL dependency Configure the appropriate JSTL library and URI.
Form value is missing Input name mismatch or incorrect request method Compare the HTML field's name with the parameter retrieved by the controller.
Characters display incorrectly Encoding mismatch Use UTF-8 consistently in the page, request handling, and response configuration.
Changes do not appear Browser cache or stale deployment artifacts Refresh the browser, redeploy if needed, and inspect container logs.
Dynamic content appears unsafe Untrusted data is rendered without contextual encoding Apply appropriate output encoding and validate input.
Servlet classes cannot be found Package, build, or API namespace mismatch Check the project build and ensure servlet imports match the target container.

22. Practical Exercises

  1. Create a JSP page that displays a welcome message supplied by a servlet.
  2. Build a form that accepts a user's name and displays a personalized greeting.
  3. Create a course listing page that loops over a collection using JSTL.
  4. Build a student dashboard that displays a student's name, course, and status.
  5. Create reusable header and footer JSP fragments.
  6. Display validation errors and success messages through request attributes.
  7. Create a profile page that uses session attributes for appropriate user-specific data.
  8. Refactor a JSP scriptlet example into a servlet controller and EL-based view.
  9. Add server-side validation and safe output encoding to a form-processing workflow.
  10. Extend the student project to load records from a database through a service and repository layer.

23. Interview Questions and Answers

Q1. What is JSP?

Answer: JSP is a server-side view technology used to create dynamic web pages by combining template content with expressions and tag libraries. The JSP container translates a JSP page into a servlet implementation.

Q2. How does JSP generate dynamic content?

Answer: The JSP container processes the page, evaluates its dynamic elements, and generates a response, typically HTML, which is sent to the browser.

Q3. What is the difference between HTML and JSP?

Answer: HTML defines page structure and content. JSP adds server-side rendering capabilities, allowing the page to display values prepared by the application.

Q4. What is the JSP lifecycle?

Answer: The container translates the JSP into servlet code, compiles it when necessary, loads the generated class, initializes the servlet, services requests, and eventually destroys the instance. Translation and compilation may occur again when the JSP changes.

Q5. What is Expression Language?

Answer: EL is a concise syntax, usually written as ${...}, for accessing attributes, bean properties, parameters, and other supported data in JSP pages.

Q6. Why should scriptlets generally be avoided?

Answer: Scriptlets mix Java logic with presentation markup, making pages harder to maintain and test. EL, JSTL, controllers, and Java classes provide cleaner separation of responsibilities.

Q7. What is JSTL?

Answer: JSTL is the JSP Standard Tag Library, which provides reusable tags for common presentation operations such as conditions, iteration, and formatting.

Q8. What is the difference between a forward and a redirect?

Answer: A forward dispatches the same server-side request to another resource. A redirect sends a response telling the browser to make a new request, changing the browser's requested URL.

Q9. How can a servlet pass data to a JSP?

Answer: A servlet can place data in request attributes using request.setAttribute() and forward to the JSP. The JSP can then access the attributes through EL.

Q10. How can JSP pages be made more secure?

Answer: Validate untrusted input, encode output for the correct context, enforce authorization on the server, use CSRF defenses for state-changing actions, and avoid exposing sensitive data or internal exceptions.

Q11. What is the difference between the include directive and the include action?

Answer: The include directive includes source content during translation. The jsp:include action includes another resource's output during request processing.

Q12. What is MVC, and how does JSP fit into it?

Answer: MVC separates model, view, and controller responsibilities. JSP usually serves as the view, a servlet or framework controller processes requests, and model/service classes manage application data and business logic.

24. Quick Revision Checklist

  • JSP is used to render dynamic server-side web content.
  • A JSP page is translated into a servlet by its container.
  • HTML provides the structure, while EL and tags provide dynamic values.
  • Directives configure JSP pages and include resources.
  • EL commonly uses the ${...} syntax.
  • JSTL supports conditions, iteration, and other presentation tasks.
  • Servlets and controllers should handle request processing.
  • JavaBeans and service classes help separate data from presentation.
  • Request, session, application, and page scopes have different lifetimes.
  • Input validation and output encoding are essential for security.
  • MVC improves maintainability by separating responsibilities.
  • Container and dependency versions must be compatible.

25. Conclusion

Creating dynamic web pages using JSP is an important skill in Advanced Java web development. JSP enables applications to display personalized content, process prepared data, reuse page components, and work with servlets and Java-based services. By understanding JSP directives, Expression Language, JSTL, scopes, and MVC architecture, developers can build web applications that are easier to maintain, test, and secure.

For production applications, keep business logic in Java classes and controllers, use JSP primarily as a presentation layer, and apply proper validation and output encoding whenever dynamic content is displayed.

Further Learning

Explore the Advanced Java Training Course for related topics in Java web application development, and use the course demo registration page to learn more.

Official reference: Jakarta Pages Specification and Jakarta EE guide to Servlets and Server Pages.

Previous Next
whatsapp